package com.common.controller;

import cn.hutool.json.JSONObject;
import com.common.enums.ApiResult;
import com.common.exception.ErrorException;
import com.common.groovy.model.DataModel;
import com.common.model.SystemApplicationServiceModel;
import com.common.sevice.SystemApplicationModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Date: 2025/7/23 08:47
 */
@RestController
@RequestMapping("/v1/system-sql")
public class SystemSqlController {

    @Autowired
    private SystemApplicationModelService applicationModelService;


    @GetMapping("/getTableSql")
    public ApiResult getTableSql(@RequestParam(required = false) String id){
        if (!StringUtils.hasText(id)){
            throw new ErrorException("主键信息不能为空");
        }
        SystemApplicationServiceModel serviceModel = applicationModelService.getById(id);
        if (ObjectUtils.isEmpty(serviceModel)){
            throw new ErrorException("模型信息不存在");
        }
        String type = serviceModel.getType();
        if (!"3".equals(type)){
            throw new ErrorException("模型类型不正确，无法生成sql脚本");
        }
        JSONObject data = serviceModel.getData();
        DataModel dataModel = data.toBean(DataModel.class);
        DataModel.Table table = dataModel.getTable();
        StringBuffer sql = new StringBuffer("CREATE TABLE `");
        if (ObjectUtils.isEmpty(table)){
            throw new ErrorException("表信息不能为空");
        }
        sql.append(table.getName()).append("`( \n");
        List<DataModel.Field> fieldList = dataModel.getField();
        List<String> primaryKeyList = new LinkedList<>();
        for (DataModel.Field field : fieldList) {
            if (field.getPrimaryKey()){
                primaryKeyList.add(field.getName());
            }
            sql.append("`").append(field.getName()).append("` ");
            String fieldType = field.getType();
            if ("varchar".equals(fieldType) || "char".equals(fieldType)){
                sql.append(fieldType).append("(").append(field.getMaxLength()).append(")");
                sql.append(" CHARACTER SET ").append(field.getCharset());
                sql.append(" COLLATE ").append(field.getCollate());
            }else if ("decimal".equals(fieldType)){
                sql.append(fieldType).append("(").append(field.getMaxLength()).append(",").append(field.getDecimalDigits()).append(")");
            }else {
                sql.append(fieldType);
            }
            if (!ObjectUtils.isEmpty(field.getRequired()) && field.getRequired()){
                sql.append(" NOT NULL ");
            }
            if (StringUtils.hasText(field.getDefaultValue())) {
                sql.append(" DEFAULT ").append(field.getDefaultValue());
            } else if (ObjectUtils.isEmpty(field.getRequired()) || !field.getRequired()) {
                sql.append(" DEFAULT NULL ");
            }
            if (!ObjectUtils.isEmpty(field.getUpdateByCurrentTime()) && field.getUpdateByCurrentTime()){
                sql.append(" ON UPDATE CURRENT_TIMESTAMP ");
            }
            if (StringUtils.hasText(field.getComment())){
                sql.append(" COMMENT '").append(field.getComment()).append("'");
            }
            sql.append(",\n");
        }

        if (!CollectionUtils.isEmpty(primaryKeyList)){
            sql.append("PRIMARY KEY (");
            String join = String.join(",", primaryKeyList.stream()
                    .map(s -> "`" + s + "`")
                    .collect(Collectors.toList()));
            sql.append(join).append(")  USING BTREE \n");
        }
        sql.append(") ENGINE=").append(table.getEngine()).append(" DEFAULT CHARSET=").append(table.getCharset()).append(" COLLATE=").append(table.getCollate()).append(";");
        return ApiResult.success(sql.toString());
    }
}
